<template>
  <div class="peer-review">
    <div class="header">
      <h2>作业互评</h2>
      <p>以下是您需要评分的作业，请逐一完成评分后提交。</p>
    </div>

    <!-- 表格内容 -->
    <div class="table-wrapper">
      <el-table
          :data="assignments"
          border
          stripe
          class="peer-review-table"
      >
        <el-table-column prop="title" label="作业标题" />
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
                type="primary"
                size="medium"
                @click="downloadFile(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="评分">
          <template v-slot="scope">
            <el-input-number
                v-model="scope.row.score"
                :min="1"
                :max="10"
                :step="1"
                placeholder="1-10 分"
                size="medium"
                controls-position="right"
                class="score-input"
            />
          </template>
        </el-table-column>
        <el-table-column label="提交评分">
          <template v-slot="scope">
            <el-button
                type="success"
                size="medium"
                :disabled="!scope.row.score"
                @click="submitSingleReview(scope.row)"
            >
              提交
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import axios from 'axios';
import { BASE_URL } from '@/config';

export default {
  props: ['id'],
  data() {
    return {
      assignments: [], // 保存作业列表
    };
  },
  created() {
    // 调用 API 加载作业数据
    this.loadAssignmentData();
  },
  methods: {
    // 加载作业数据
    async loadAssignmentData() {
      const homework_id = this.$route.query.homework_id; // 从路由参数中获取 homework_id
      console.log("homework_id", homework_id);
      if (!homework_id) {
        this.$message.error('homework_id 缺失，无法加载作业数据！');
        return;
      }

      try {
        const response = await axios.post(`${BASE_URL}/evaluation/getEvaluation`, {
          evaluator: window.sessionStorage.getItem('userId'),
          homework_id,
        });
        console.log('API 响应:', response.data);

        if (response.data.code === 200) {
          // 使用后端返回的 score 值
          this.assignments = response.data.data.map((assignment) => ({
            ...assignment,
            submitted: false, // 添加是否提交的标记字段
          }));
        } else {
          this.$message.error('加载作业数据失败！');
        }
      } catch (error) {
        console.error('加载作业数据失败:', error);
        this.$message.error('加载作业数据失败，请检查网络连接！');
      }
    },

    // 提交单个评分
    async submitSingleReview(assignment) {
      if (!assignment.score) {
        this.$message.error('评分不能为空！');
        return;
      }

      try {
        const response = await axios.post(`${BASE_URL}/evaluation/evaluate`, {
          evaluator: window.sessionStorage.getItem('userId'),
          evaluated: assignment.stu_id,
          homework_id: assignment.homework_id,
          score: assignment.score,
        });

        if (response.data.code === 200) {
          this.$message.success('评分提交成功！');
          assignment.submitted = true; // 标记该作业已提交
        } else {
          this.$message.error('评分提交失败，请重试！');
        }
      } catch (error) {
        console.error('提交评分失败:', error);
        this.$message.error('提交评分失败，请检查网络连接！');
      }
    },

    // 下载文件
    async downloadFile(assignment) {
      try {
        // 发送 POST 请求
        const response = await axios.post(`${BASE_URL}/homework/downloadSub`, {
          stu_id: assignment.stu_id,
          homework_id: assignment.homework_id,
        });

        // 假设后端返回的数据是 Base64 格式
        const base64Data = response.data.data.content; // 确保 data 是 Base64 字符串
        const mimeType = "application/pdf"; // 设置文件的 MIME 类型
        const blob = this.base64ToBlob(base64Data, mimeType);
        const name = response.data.data.fileName;

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;

        // 设置文件名
        link.setAttribute("download", `${name}`);
        document.body.appendChild(link);
        link.click();

        // 清理资源
        link.remove();
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error("文件下载失败:", error);
        this.$message.error("文件下载失败");
      }
    },

    // Base64 转 Blob 工具函数
    base64ToBlob(base64, mimeType) {
      const byteCharacters = atob(base64); // 解码 Base64
      const byteNumbers = new Array(byteCharacters.length)
          .fill(0)
          .map((_, i) => byteCharacters.charCodeAt(i));
      const byteArray = new Uint8Array(byteNumbers);
      return new Blob([byteArray], { type: mimeType });
    },
  },
};
</script>
<style scoped>
.peer-review {
  display: flex;
  flex-direction: column;
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中 */
  padding: 40px;
  width: 100%;
  min-height: 100vh; /* 保证页面占满全屏 */
  background: linear-gradient(135deg, #e3f2fd, #ffffff); /* 蓝色背景适配整个页面 */
  box-sizing: border-box;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h2 {
  font-size: 32px;
  color: #1976d2; /* 更鲜明的颜色 */
  font-weight: bold;
  margin-bottom: 10px;
}

.header p {
  color: #666;
  font-size: 18px;
}

.table-wrapper {
  width: 80%; /* 表格容器宽度增加到 80% */
  max-width: 1400px; /* 限制表格最大宽度 */
  margin: 0 auto;
  background: #ffffff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1); /* 卡片式阴影 */
}

.peer-review-table {
  width: 100%;
  font-size: 16px;
  background-color: white;
}

.el-table th {
  text-align: center;
  font-size: 18px;
  color: #1976d2; /* 表头颜色 */
}

.el-table td {
  text-align: center;
}

.actions {
  width: 80%; /* 与表格宽度一致 */
  max-width: 1400px;
  display: flex;
  justify-content: center; /* 居中按钮 */
  padding-top: 20px;
}

.score-input {
  width: 100%; /* 确保评分输入框填满列宽 */
}

</style>
